/*
 * ConfigurationReader.cs
 *
 * Reads setting from dll.config or app.config.
 *
 * Copyright (c) 2005, dnAnalytics. All rights reserved.
 */

#region Using Directives

using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Xml;

#endregion Using Directives

namespace dnAnalytics.Nli {
	internal sealed class ConfigurationReader {
		private static NameValueCollection keyValues = new NameValueCollection();
		private static string configFile = Assembly.GetCallingAssembly().CodeBase + ".config";
		private static string[] dnAsettings = {"dnAnalytics.blas.dll", "dnAnalytics.lapack.dll"};

		static ConfigurationReader() {
			ReadDllConfig();
			ReadAppSettings();
		}

		private ConfigurationReader() {}

		private static void ReadAppSettings() {
            NameValueCollection config = ConfigurationSettings.AppSettings;
			foreach (string key in config.AllKeys) {
				foreach (string dnAsetting in dnAsettings) {
					if (key.Equals(dnAsetting)) {
						keyValues.Add(key, config[key]);
					}
				}
			}
		}

		private static void ReadDllConfig() {
			XmlDocument doc = new XmlDocument();
			try {
				doc.Load(new XmlTextReader(configFile));
			} catch (FileNotFoundException) {
				Trace.WriteLine("dnAnalytics config file : " + configFile + " not found.");
				//do nothing since the config file doesn't exist
				return;
			}

			XmlNodeList appSettings = doc.GetElementsByTagName("appSettings");
			foreach (XmlNode node in appSettings) {
				XmlNodeList settings = node.ChildNodes;
				foreach (XmlNode setting in settings) {
					if (setting.LocalName == "add") {
						XmlElement item = (XmlElement) setting;
						string key = item.GetAttribute("key");
						string value = item.GetAttribute("value");
						foreach (string dnAsetting in dnAsettings) {
							if (key.Equals(dnAsetting)) {
								keyValues.Add(key, value);
							}
						}
					}
				}
			}
		}

		public static string Setting(string setting) {
			return keyValues[setting];
		}
	}
}